package com.guldan.jaina.manager;

import java.util.ArrayList;
import java.util.List;

import com.guldan.core.exception.BusinessException;
import com.guldan.jaina.utils.CitizenInfoDomainConvertUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.guldan.core.manager.BaseManager;
import com.guldan.core.search.Pagination;
import com.guldan.core.utils.DateUtil;
import com.guldan.jaina.dto.citizenbank.CitizenBankDTO;
import com.guldan.jaina.dto.citizenbank.CitizenBankSearchDTO;
import com.guldan.mapper.db.entity.CitizenBank;
import com.guldan.mapper.db.entity.CitizenBankExample;
import com.guldan.mapper.db.mapper.CitizenBankMapperExt;

/**
 * Created by Silas.
 * Date: 2016/11/7
 * Time: 22:55
 */
@Service
public class CitizenBankManager extends BaseManager {

    @Autowired
    private CitizenBankMapperExt citizenBankMapperExt;

    //获取单个居民银行信息
    public CitizenBankDTO get(Integer id) {
        return CitizenInfoDomainConvertUtils.convert(citizenBankMapperExt.selectByPrimaryKey(id));
    }

    //获取单个居民银行信息，通过居民信息id
    public List<CitizenBankDTO> getByCitizenInfoId(Integer citizenInfoId) {
        CitizenBankSearchDTO search = new CitizenBankSearchDTO();
        search.setCitizenInfoId(citizenInfoId);
        List<CitizenBank> entityList = citizenBankMapperExt.selectByExample(buildSearchExample(search));
        List<CitizenBankDTO> dtoList = new ArrayList<>();
        if (entityList != null && entityList.size() > 0) {
            for (CitizenBank entity : entityList) {
                dtoList.add(CitizenInfoDomainConvertUtils.convert(entity));
            }
        }
        return dtoList;
    }

    public List<CitizenBankDTO> getByBankCodeAndNumber(String bankCode, String bankNumber) {
        CitizenBankSearchDTO search = new CitizenBankSearchDTO();
        search.setBankCode(bankCode);
        search.setBankNumber(bankNumber);
        List<CitizenBank> entityList = citizenBankMapperExt.selectByExample(buildSearchExample(search));
        List<CitizenBankDTO> dtoList = new ArrayList<>();
        if (entityList != null && entityList.size() > 0) {
            for (CitizenBank entity : entityList) {
                dtoList.add(CitizenInfoDomainConvertUtils.convert(entity));
            }
        }
        return dtoList;
    }

    //新增/更新单个居民银行，传入：CitizenBankDTO
    public CitizenBankDTO save(CitizenBankDTO dto) {

        CitizenBank entity;
        if (dto.getCitizenBankId() != null && dto.getCitizenBankId() > 0) {
            entity = citizenBankMapperExt.selectByPrimaryKey(dto.getCitizenBankId());
            entity.setBankCode(dto.getBankCode());
            entity.setBankNumber(dto.getBankNumber());
            entity.setCitizenInfoId(dto.getCitizenInfoId());
            entity.setModifyTime(DateUtil.getCurrentTime());
            entity.setModifier(dto.getModifier());
            entity.setIsDelete(false);
            entity.setDisabled(false);
            citizenBankMapperExt.updateByPrimaryKeySelective(entity);
        } else {
            entity = new CitizenBank();
            entity.setBankCode(dto.getBankCode());
            entity.setBankNumber(dto.getBankNumber());
            entity.setCitizenInfoId(dto.getCitizenInfoId());
            entity.setCreator(dto.getCreator());
            entity.setCreateTime(DateUtil.getCurrentTime());
            citizenBankMapperExt.insertSelective(entity);
        }
        dto = CitizenInfoDomainConvertUtils.convert(entity);
        return dto;
    }

    public List<CitizenBankDTO> saveList(Integer citizenInfoId, List<CitizenBankDTO> saveDtos) throws BusinessException {

        if (saveDtos == null) {
            saveDtos = new ArrayList<>();
        }

        //先判断需要保存的银行卡列表是否有重复的卡号记录
        if (saveDtos != null && saveDtos.size() > 0) {
            for (CitizenBankDTO dto : saveDtos) {
                int i = 0;
                for (CitizenBankDTO dto1 : saveDtos) {
                    if (dto.getBankNumber().equals(dto1.getBankNumber())) {
                        i++;
                    }
                }
                if (i > 1) {
                    throw new BusinessException("保存的银行卡列表中有重复的卡号：" + dto.getBankNumber());
                }
            }
        }


        CitizenBankSearchDTO search = new CitizenBankSearchDTO();
        search.setCitizenInfoId(citizenInfoId);
        List<CitizenBank> historyList = citizenBankMapperExt.selectByExample(buildSearchExample(search));

        //先将需要删除的银行卡进行删除
        if (historyList != null && historyList.size() > 0) {
            for (CitizenBank history : historyList) {
                Boolean needDelete = true;
                for (CitizenBankDTO dto : saveDtos) {
                    //如果发现有表的记录存在需要保存的记录里，则需要保留（银行卡号一致）
                    if (dto.getCitizenBankId() != null && history.getBankNumber().equals(dto.getBankNumber())) {
                        needDelete = false;
                        break;
                    }
                }
                if (needDelete) {
                    //进行删除
                    history.setIsDelete(true);
                    citizenBankMapperExt.updateByPrimaryKeySelective(history);
                }
            }
        }
        //将需要保存、新增的银行卡进行保存
        for (CitizenBankDTO dto : saveDtos) {
            dto.setCitizenInfoId(citizenInfoId);
            save(dto);
        }
        //编辑修改后重新获取银行卡信息列表
        return getByCitizenInfoId(citizenInfoId);
    }

    //删除单个居民银行信息
    public Boolean delete(Integer id) {
        CitizenBank entity = citizenBankMapperExt.selectByPrimaryKey(id);
        entity.setIsDelete(true);
        return citizenBankMapperExt.updateByPrimaryKeySelective(entity) > 0;
    }

    //删除单个居民银行信息
    public Boolean deleteByCitizenInfoId(Integer citizenInfoId) {
        CitizenBank update = new CitizenBank();
        update.setIsDelete(true);
        update.setModifyTime(DateUtil.getCurrentTime());

        CitizenBankExample example = new CitizenBankExample();
        CitizenBankExample.Criteria criteria = example.createCriteria();
        criteria.andCitizenInfoIdEqualTo(citizenInfoId);
        criteria.andIsDeleteEqualTo(false);

        citizenBankMapperExt.updateByExampleSelective(update,example);
        return true;
    }

    //验证银行卡是否已经添加过
    public Boolean checkExist(List<CitizenBankDTO> list) {
        Boolean ret = false;
        for (CitizenBankDTO dto : list) {
            if (checkExist(dto)) {
                ret = true;
                break;
            }
        }
        return ret;
    }

    public CitizenBankDTO getByCodeAndNumber(String bankCode, String bankNumber) {
        CitizenBankExample example = new CitizenBankExample();
        CitizenBankExample.Criteria criteria = example.createCriteria();
        criteria.andBankCodeEqualTo(bankCode);
        criteria.andBankNumberEqualTo(bankNumber);
        criteria.andIsDeleteEqualTo(false);
        List<CitizenBank> entityList = citizenBankMapperExt.selectByExample(example);
        CitizenBankDTO dto = new CitizenBankDTO();
        if (entityList != null && entityList.size() > 0) {
            dto = CitizenInfoDomainConvertUtils.convert(entityList.get(0));
        } else {
            dto = null;
        }
        return dto;
    }

    //
    public CitizenBankDTO getByNumber(String bankNumber) {
        CitizenBankExample example = new CitizenBankExample();
        CitizenBankExample.Criteria criteria = example.createCriteria();
        criteria.andBankNumberEqualTo(bankNumber);
        criteria.andIsDeleteEqualTo(false);
        List<CitizenBank> entityList = citizenBankMapperExt.selectByExample(example);
        CitizenBankDTO dto = new CitizenBankDTO();
        if (entityList != null && entityList.size() > 0) {
            dto = CitizenInfoDomainConvertUtils.convert(entityList.get(0));
        } else {
            dto = null;
        }
        return dto;
    }





    //验证银行卡是否已经添加过
    public Boolean checkExist(CitizenBankDTO dto) {
        Boolean ret = false;
        CitizenBankExample example = new CitizenBankExample();
        CitizenBankExample.Criteria criteria = example.createCriteria();
        criteria.andIsDeleteEqualTo(false);
        criteria.andBankNumberEqualTo(dto.getBankNumber());
        criteria.andBankCodeEqualTo(dto.getBankCode());

        List<CitizenBank> entityList = citizenBankMapperExt.selectByExample(example);
        if (entityList != null && entityList.size() > 0) {
            //已经存在
            ret = true;
        }
        return ret;
    }

    //分页查询居民银行信息列表
    public Pagination<CitizenBankDTO> list(CitizenBankSearchDTO citizenBankSearchDTO) {
        Pagination<CitizenBankDTO> result = new Pagination<CitizenBankDTO>(citizenBankSearchDTO.getCurrentPage(), citizenBankSearchDTO.getPerPage());
        CitizenBankExample example = buildSearchExample(citizenBankSearchDTO);
        int total = citizenBankMapperExt.countByExample(example);
        result.setTotalCount(total);
        if (total > 0) {
            List<CitizenBankDTO> data = new ArrayList<CitizenBankDTO>();
            List<CitizenBank> list = citizenBankMapperExt.selectByExampleWithPaging(example, result.getOffset(), result.getPageSize());
            for (CitizenBank entity : list) {
                CitizenBankDTO dto = CitizenInfoDomainConvertUtils.convert(entity);
                data.add(dto);
            }
            result.setList(data);
        }
        return result;
    }

    /**
     * @param citizenBankSearchDTO
     * @return
     */
    public List<CitizenBankDTO> getCitizenBankList(CitizenBankSearchDTO citizenBankSearchDTO) {
        CitizenBankExample example = new CitizenBankExample();
        CitizenBankExample.Criteria criteria = example.createCriteria();
        if (citizenBankSearchDTO.getCitizenInfoId() != null && citizenBankSearchDTO.getCitizenInfoId() > 0) {
            criteria.andCitizenInfoIdEqualTo(citizenBankSearchDTO.getCitizenInfoId());
        }
        criteria.andIsDeleteEqualTo(false);
        List<CitizenBank> citizenBankList = citizenBankMapperExt.selectByExample(example);
        List<CitizenBankDTO> data = new ArrayList<CitizenBankDTO>();
        for (CitizenBank entity : citizenBankList) {
            CitizenBankDTO dto = CitizenInfoDomainConvertUtils.convert(entity);
            data.add(dto);
        }
        return data;
    }


    //build查询Example
    private CitizenBankExample buildSearchExample(CitizenBankSearchDTO search) {
        CitizenBankExample example = new CitizenBankExample();
        CitizenBankExample.Criteria criteria = example.createCriteria();

        if (search.getCitizenBankId() != null && search.getCitizenBankId() > 0) {
            criteria.andCitizenBankIdEqualTo(search.getCitizenBankId());
        }
        if (search.getCitizenInfoId() != null && search.getCitizenInfoId() > 0) {
            criteria.andCitizenInfoIdEqualTo(search.getCitizenInfoId());
        }
        if (StringUtils.isNotBlank(search.getBankCode())) {
            criteria.andBankCodeEqualTo(search.getBankCode());
        }
        if (StringUtils.isNotBlank(search.getBankNumber())) {
            criteria.andBankNumberEqualTo(search.getBankNumber());
        }
        criteria.andIsDeleteEqualTo(Boolean.FALSE);
        if (StringUtils.isNotBlank(search.getOrderByClause())) {
            example.setOrderByClause(search.getOrderByClause());
        } else {
            example.setOrderByClause("citizen_bank_id asc");
        }
        return example;
    }

}
